<template>
  <div class="layout">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="container">
        <div class="nav-container">
          <div class="logo">
            <h2>前端开发技术课程</h2>
          </div>
          <el-menu
            :default-active="activeIndex"
            class="nav-menu"
            mode="horizontal"
            @select="handleSelect"
            background-color="transparent"
            text-color="#fff"
            active-text-color="#ffd04b"
          >
            <el-menu-item index="/">首页</el-menu-item>
            <el-menu-item index="/experiments">实验</el-menu-item>
            <el-menu-item index="/lectures">讲义</el-menu-item>
            <el-menu-item index="/videos">课程视频</el-menu-item>
          </el-menu>
          <div class="user-actions">
            <template v-if="!isLoggedIn">
              <el-button type="primary" @click="showLogin = true">登录</el-button>
              <el-button @click="showRegister = true">注册</el-button>
            </template>
            <template v-else>
              <el-dropdown @command="handleCommand">
                <span class="user-info">
                  <el-avatar :size="32" :src="userInfo.avatar" icon="User" />
                  <span class="username">{{ userInfo.name }}</span>
                  <el-icon><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                    <el-dropdown-item command="progress">学习进度</el-dropdown-item>
                    <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </div>
        </div>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main-content">
      <router-view />
    </el-main>

    <!-- 页脚 -->
    <el-footer class="footer">
      <div class="container">
        <p>&copy; 2024 前端开发技术课程. All rights reserved.</p>
      </div>
    </el-footer>

    <!-- 登录对话框 -->
    <el-dialog v-model="showLogin" title="用户登录" width="400px">
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showLogin = false">取消</el-button>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </template>
    </el-dialog>

    <!-- 注册对话框 -->
    <el-dialog v-model="showRegister" title="用户注册" width="400px">
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const showLogin = ref(false)
const showRegister = ref(false)
const isLoggedIn = ref(false)
const userInfo = ref({
  name: '',
  avatar: '',
  email: ''
})

// 表单数据
const loginForm = ref({
  username: '',
  password: ''
})

const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const activeIndex = computed(() => route.path)

// 方法
const handleSelect = (key) => {
  router.push(key)
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'progress':
      router.push('/progress')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogin = async () => {
  // 模拟登录逻辑
  try {
    // 这里应该调用实际的登录API
    isLoggedIn.value = true
    userInfo.value = {
      name: loginForm.value.username,
      avatar: '',
      email: ''
    }
    showLogin.value = false
    ElMessage.success('登录成功')
    
    // 保存登录状态到localStorage
    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  } catch (error) {
    ElMessage.error('登录失败')
  }
}

const handleRegister = async () => {
  // 模拟注册逻辑
  try {
    // 这里应该调用实际的注册API
    showRegister.value = false
    ElMessage.success('注册成功，请登录')
    showLogin.value = true
  } catch (error) {
    ElMessage.error('注册失败')
  }
}

const handleLogout = () => {
  isLoggedIn.value = false
  userInfo.value = { name: '', avatar: '', email: '' }
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('userInfo')
  ElMessage.success('已退出登录')
  router.push('/')
}

// 生命周期
onMounted(() => {
  // 检查本地存储的登录状态
  const savedLoginStatus = localStorage.getItem('isLoggedIn')
  const savedUserInfo = localStorage.getItem('userInfo')
  
  if (savedLoginStatus === 'true' && savedUserInfo) {
    isLoggedIn.value = true
    userInfo.value = JSON.parse(savedUserInfo)
  }
})
</script>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
  height: 70px;
  line-height: 70px;
}

.nav-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.logo h2 {
  color: white;
  margin: 0;
  font-size: 1.5rem;
}

.nav-menu {
  flex: 1;
  justify-content: center;
  border-bottom: none;
}

.nav-menu .el-menu-item {
  border-bottom: none;
  font-size: 16px;
  font-weight: 500;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  cursor: pointer;
}

.username {
  font-size: 14px;
}

.main-content {
  flex: 1;
  padding: 0;
  background-color: #f5f7fa;
}

.footer {
  background-color: #2c3e50;
  color: white;
  text-align: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    flex-direction: column;
    height: auto;
    padding: 10px 0;
  }
  
  .logo {
    margin-bottom: 10px;
  }
  
  .nav-menu {
    width: 100%;
    justify-content: space-around;
  }
  
  .user-actions {
    margin-top: 10px;
  }
  
  .header {
    height: auto;
    line-height: normal;
  }
}
</style>